package rpc

import (
	"context"
	"encoding/json"
	proto "gykjgit.dccnet.com.cn/chain/proto/swarm"
	"gykjgit.dccnet.com.cn/chain/swarm/client"
)

type ImageServer struct {
}

func (i *ImageServer) List(ctx context.Context, _ *proto.ReqImageList) (*proto.RespImageList, error) {
	images, err := client.Obtain().Image().List(ctx)
	if nil != err {
		return &proto.RespImageList{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	data, err := json.Marshal(images)
	if nil != err {
		return &proto.RespImageList{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	return &proto.RespImageList{Code: proto.Code_success, Images: data}, nil
}

func (i *ImageServer) Pull(ctx context.Context, in *proto.ReqImagePull) (*proto.RespImagePull, error) {
	if err := client.Obtain().Image().Pull(ctx, in.RefStr); nil != err {
		return &proto.RespImagePull{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	return &proto.RespImagePull{Code: proto.Code_success}, nil
}

func (i *ImageServer) Remove(ctx context.Context, in *proto.ReqImageRemove) (*proto.RespImageRemove, error) {
	images, err := client.Obtain().Image().Remove(ctx, in.ID)
	if nil != err {
		return &proto.RespImageRemove{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	data, err := json.Marshal(images)
	if nil != err {
		return &proto.RespImageRemove{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	return &proto.RespImageRemove{Code: proto.Code_success, ImageItems: data}, nil
}

func (i *ImageServer) Tag(ctx context.Context, in *proto.ReqImageTag) (*proto.RespImageTag, error) {
	if err := client.Obtain().Image().Tag(ctx, in.Source, in.Target); nil != err {
		return &proto.RespImageTag{Code: proto.Code_fail, ErrMsg: err.Error()}, err
	}
	return &proto.RespImageTag{Code: proto.Code_success}, nil
}
